'use strict'

module.exports = (function(){
    var redis = require('redis');
    let Fiber = require('fibers');
    var outputLogger = require('../lib/loggers').output;

    class RedisClient {
        constructor() {
            this.client = redis.createClient();

            this.client.on('error', function(error) {
                outputLogger.error(error);
            });
        }

        quit() {
            this.client.quit();
        }

        select(number) {
            let fiber = Fiber.current;

            this.client.select(number, function() {
                fiber.run();
            });

            Fiber.yield();

            return true;
        }

        lpop(key) {
            let fiber = Fiber.current;

            let error = null;
            let value = null;
            this.client.lpop(key, (err, result) => {
                if ( err ) {
                    error = err;
                }

                value = result;

                fiber.run();
            });

            Fiber.yield();

            if ( error ) {
                throw error;
            }

            return value;
        }

        rpush(key, value) {
            let fiber = Fiber.current;

            let error = null;
            this.client.rpush(key, value, (err, result) => {
                if ( err ) {
                    error = err;
                }

                fiber.run();
            });

            Fiber.yield();

            if ( error ) {
                throw error;
            }

            return true;
        }
    }

    function CreateClient() {
        return new RedisClient();
    }

    return {
        getClient: CreateClient
    };
}());
